package com.athena.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.athena.common.helper.LoginHelper;
import com.athena.common.utils.StringUtils;
import com.athena.common.core.page.TableDataInfo;
import com.athena.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.athena.crm.constant.CommonConstant;
import com.athena.crm.domain.*;
import com.athena.crm.domain.bo.CrmCluePoolToClueBo;
import com.athena.crm.domain.bo.CrmClueTransferBo;
import com.athena.crm.domain.bo.CrmCustomerToHighSeasBo;
import com.athena.crm.domain.vo.CrmClueVo;
import com.athena.crm.domain.vo.CrmCustomerVo;
import com.athena.crm.mapper.CrmClueFollrecordsMapper;
import com.athena.crm.mapper.CrmClueMapper;
import com.athena.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.athena.crm.domain.bo.CrmCluePoolBo;
import com.athena.crm.domain.vo.CrmCluePoolVo;
import com.athena.crm.mapper.CrmCluePoolMapper;
import com.athena.crm.service.ICrmCluePoolService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * CRM线索池Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-10
 */
@Slf4j
@RequiredArgsConstructor
@Transactional
@Service
public class CrmCluePoolServiceImpl implements ICrmCluePoolService {

    private final CrmCluePoolMapper baseMapper;

    private final CrmClueMapper crmClueMapper;

    private final ISysDeptService sysDeptService;

    private final CrmClueFollrecordsMapper crmClueFollrecordsMapper;

    /**
     * 查询CRM线索池
     */
    @Override
    public CrmCluePoolVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询CRM线索池列表
     */
    @Override
    public TableDataInfo<CrmCluePoolVo> queryPageList(CrmCluePoolBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CrmCluePool> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(CrmCluePool::getUpdateTime);
        Page<CrmCluePoolVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<CrmCluePoolVo> crmCluePoolVos = result.getRecords();
        for (CrmCluePoolVo crmCluePoolVo:crmCluePoolVos) {
            String deptPaht = sysDeptService.getDeptPath(crmCluePoolVo.getFormerDeptId(), "");
            crmCluePoolVo.setFormerDept(deptPaht);
        }
        return TableDataInfo.build(result);
    }


    /**
     * 查询CRM线索池列表
     */
    @Override
    public List<CrmCluePoolVo> queryList(CrmCluePoolBo bo) {
        LambdaQueryWrapper<CrmCluePool> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(CrmCluePool::getUpdateTime);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CrmCluePool> buildQueryWrapper(CrmCluePoolBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CrmCluePool> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), CrmCluePool::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), CrmCluePool::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getCompany()), CrmCluePool::getCompany, bo.getCompany());
        lqw.eq(StringUtils.isNotBlank(bo.getCluesSources()), CrmCluePool::getCluesSources, bo.getCluesSources());
        lqw.eq(StringUtils.isNotBlank(bo.getFormerHead()), CrmCluePool::getFormerHead, bo.getFormerHead());
        if(bo.getFormerDeptId() != null) {
            lqw.eq(StringUtils.isNotBlank(bo.getFormerDeptId().toString()), CrmCluePool::getFormerDeptId, bo.getFormerDeptId());
        }
        lqw.eq(bo.getLastIntoTime() != null, CrmCluePool::getLastIntoTime, bo.getLastIntoTime());
        return lqw;
    }

    /**
     * 新增CRM线索池
     */
    @Override
    public Boolean insertByBo(CrmCluePoolBo bo) {
        CrmCluePool add = BeanUtil.toBean(bo, CrmCluePool.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改CRM线索池
     */
    @Override
    public Boolean updateByBo(CrmCluePoolBo bo) {
        CrmCluePool update = BeanUtil.toBean(bo, CrmCluePool.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CrmCluePool entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除CRM线索池
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean insertByBbo(CrmClueTransferBo bbo) {
        String[] idList = bbo.getIds().split(",");
        List<CrmCluePool> crmCluePools = new ArrayList<>();
        List<CrmClueFollrecords> crmClueFollrecordss = new ArrayList<>();
        List<CrmClue> crmClues = new ArrayList<>();
        List<CrmClueVo> crmClueVos = crmClueMapper.selectVoBatchIds(Arrays.asList(idList));
        for (CrmClueVo crmClueVo:crmClueVos) {
            CrmCluePool crmCluePool = new CrmCluePool();
            crmCluePool.setClueId(crmClueVo.getId() + "");
            crmCluePool.setName(crmClueVo.getName());
            crmCluePool.setPhone(crmClueVo.getPhone());
            crmCluePool.setCompany(crmClueVo.getComName());
            crmCluePool.setCluesSources(crmClueVo.getCluesSources());
            crmCluePool.setFormerHead(crmClueVo.getHead());
            if (crmClueVo.getDeptId() != null) {
                crmCluePool.setFormerDeptId(crmClueVo.getDeptId());
            }
            crmCluePool.setLastIntoTime(new Date());
            crmCluePools.add(crmCluePool);

            CrmClue crmClue = BeanUtil.toBean(crmClueVo, CrmClue.class);
            crmClues.add(crmClue);

            CrmClueFollrecords crmClueFollrecords = new CrmClueFollrecords();
            crmClueFollrecords.setClueId(crmClueVo.getId() + "");
            crmClueFollrecords.setFollowUser(LoginHelper.getLoginUser().getUsername());
            crmClueFollrecords.setFollowContent("线索[" + crmClue.getName() + "]转线索池");
            crmClueFollrecords.setFlowType(CommonConstant.FOLLOW_TYPE_OPERATE_LOG);
            crmClueFollrecordss.add(crmClueFollrecords);
        }
        for (CrmClue crmClue:crmClues) {
            crmClue.setIsDeleted("1");
        }
        baseMapper.insertBatch(crmCluePools);
        crmClueMapper.updateBatchById(crmClues);
        crmClueFollrecordsMapper.insertBatch(crmClueFollrecordss);
        return true;
    }

    @Override
    public CrmCluePoolVo queryByNameAndPhone(String name, String phone) {
        LambdaQueryWrapper<CrmCluePool> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(name), CrmCluePool::getName, name);
        lqw.eq(StringUtils.isNotBlank(phone), CrmCluePool::getPhone, phone);
        List<CrmCluePoolVo> crmClueVos = baseMapper.selectVoList(lqw);
        if (!CollectionUtils.isEmpty(crmClueVos)) {
            return crmClueVos.get(0);
        }
        return null;
    }

    @Override
    public int cluePooltoClue(CrmCluePoolToClueBo bbo) {
        log.info("线索池 ID {} 转线索", bbo.getIds());
        String[] ids = bbo.getIds().split(",");
        List<CrmCluePool> crmCluePools = baseMapper.selectBatchIds(Arrays.asList(ids));
        List<String> clueIds =  crmCluePools.stream().map(CrmCluePool::getClueId).collect(Collectors.toList());
        List<CrmClueVo> crmClueVos = crmClueMapper.selectVoBatchIds(clueIds);
        List<CrmClue> crmClues = new ArrayList<>();
        List<CrmClueFollrecords> crmClueFollrecordsList = new ArrayList<>();
        for (CrmClueVo crmClueVo:crmClueVos) {
            log.info("线索ID: {}, name: {}", crmClueVo.getId(), crmClueVo.getName());
            CrmClue crmClue = BeanUtil.toBean(crmClueVo, CrmClue.class);
            crmClue.setClueStatus("线索");
            crmClue.setFollowStatus("未处理");
            crmClue.setLatestFollowRecords("");
            crmClue.setHead(LoginHelper.getLoginUser().getUsername());
            crmClue.setDeptId(LoginHelper.getLoginUser().getDeptId());
            crmClue.setDeptName(LoginHelper.getLoginUser().getDeptName());
            crmClue.setUpdateBy(LoginHelper.getLoginUser().getUsername());
            crmClue.setRealityFollowRecords(new Date());
            crmClue.setNextFollowTime(null);
            crmClue.setUpdateTime(new Date());
            crmClue.setIsDeleted("0");
            crmClues.add(crmClue);
            //客户操作记录
            CrmClueFollrecords crmClueFollrecords = new CrmClueFollrecords();
            crmClueFollrecords.setClueId(crmClueVo.getId() + "");
            crmClueFollrecords.setFlowType(CommonConstant.FOLLOW_TYPE_OPERATE_LOG);
            crmClueFollrecords.setFollowContent("线索池转线索[" + crmClueVo.getName() + "]");
            crmClueFollrecords.setFollowUser(LoginHelper.getLoginUser().getUsername());
            crmClueFollrecordsList.add(crmClueFollrecords);
        }
        crmClueFollrecordsMapper.insertBatch(crmClueFollrecordsList);
        baseMapper.deleteBatchIds(Arrays.asList(ids));
        crmClueMapper.insertOrUpdateBatch(crmClues);
        return 1;
    }
}
